<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>旅游管理系统 - 管理页面</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body { margin: 0; background: #f0f2f5; font-family: 'Microsoft YaHei', Arial, sans-serif; }
        .layout {
            display: flex;
            height: 100vh;
        }
        .sidebar {
            width: 220px;
            background: #23272e;
            color: #fff;
            display: flex;
            flex-direction: column;
        }
        .sidebar .logo {
            font-size: 20px;
            font-weight: bold;
            padding: 24px 0 24px 32px;
            background: #1a1d22;
            letter-spacing: 2px;
        }
        .sidebar .menu {
            flex: 1;
            padding: 0;
            margin: 0;
            list-style: none;
        }
        .sidebar .menu li {
            padding: 16px 32px;
            cursor: pointer;
            transition: background 0.2s;
        }
        .sidebar .menu li:hover, .sidebar .menu .active {
            background: #1890ff;
        }
        .sidebar .menu-title {
            padding: 16px 32px 8px 32px;
            color: #aaa;
            font-size: 13px;
        }
        .main {
            flex: 1;
            display: flex;
            flex-direction: column;
            background: #f0f2f5;
        }
        .header {
            height: 56px;
            background: #fff;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 32px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.03);
        }
        .header .user-info {
            display: flex;
            align-items: center;
        }
        .header .avatar {
            width: 32px; height: 32px; border-radius: 50%; background: #eee; margin-right: 10px;
        }
        .header .username { color: #333; margin-right: 16px; }
        .header .logout { color: #1890ff; cursor: pointer; text-decoration: none; }
        .content {
            flex: 1;
            background: #fff;
            margin: 24px 24px 0 24px;
            border-radius: 8px;
            padding: 24px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }
        .table-toolbar {
            margin-bottom: 16px;
            display: flex;
            align-items: center;
            gap: 12px;
        }
        .table-toolbar input, .table-toolbar button {
            padding: 6px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        .table-toolbar button {
            background: #13c2c2; color: #fff; border: none; cursor: pointer;
            transition: background 0.2s;
        }
        .table-toolbar button:hover { background: #36cfc9; }
        .table-toolbar .search-btn { background: #1890ff; }
        .table-toolbar .search-btn:hover { background: #40a9ff; }
        .table-toolbar .reset-btn { background: #fff; color: #1890ff; border: 1px solid #1890ff; }
        .table-toolbar .reset-btn:hover { background: #e6f7ff; }
        table {
            width: 100%;
            border-collapse: collapse;
            background: #fff;
        }
        th, td {
            border: 1px solid #f0f0f0;
            padding: 10px 8px;
            text-align: center;
            font-size: 14px;
        }
        th { background: #fafafa; }
        .action-btn {
            background: #ff4d4f; color: #fff; border: none; border-radius: 4px; padding: 4px 12px; cursor: pointer; margin: 0 2px;
        }
        .action-btn.edit { background: #1890ff; }
        .action-btn:hover { opacity: 0.85; }
        .pagination {
            margin: 16px 0 0 0; text-align: right;
        }
    </style>
</head>
<body>
<div class="layout">
    <div class="sidebar">
        <div class="logo">旅游管理系统</div>
        <div class="menu-title">基本功能</div>
        <ul class="menu">
            <li onclick="showSection('user')" id="menu-user">用户管理</li>
            <li onclick="showSection('scenic')" id="menu-scenic">景点售票管理</li>
            <li onclick="showSection('productOrder')" id="menu-productOrder">门票订单管理</li>
            <li onclick="showSection('route')" id="menu-route">旅行社管理</li>
            <li onclick="showSection('scenicStandalone')" id="menu-scenic-standalone">路线管理</li>
            <li onclick="showSection('comment')" id="menu-comment">评论管理</li>
            <li onclick="showSection('routeSpot')" id="menu-route-spot"></li>

        </ul>
    </div>
    <div class="main">
        <div class="header">
            <div></div>
            <div class="user-info">
                <div class="avatar"></div>
                <span class="username">admin</span>
                <a class="logout" href="login.html">退出</a>
            </div>
        </div>
        <div class="content" id="section-comment" style="display:block;">
            <div class="table-toolbar">
                <input type="text" placeholder="评论内容">
                <input type="text" placeholder="用户ID">
                <input type="text" placeholder="景点ID">
                <button class="search-btn">搜索</button>
                <button class="reset-btn">重置</button>
                <button>添加</button>
            </div>
            <table>
                <thead>
                    <tr>
                        <th><input type="checkbox"></th>
                        <th>序号</th>
                        <th>用户名</th>
                        <th>景点</th>
                        <th>评论</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="commentTbody">
                </tbody>
            </table>
            <div class="pagination">
                <span>1</span> / <span>1</span> 页，共 <span>2</span> 条
            </div>
        </div>
        <div class="content" id="section-user" style="display:none;">
            <div class="table-toolbar">
                <input type="text" placeholder="用户名">
                <input type="text" placeholder="邮箱">
                <input type="text" placeholder="手机号">
                <button class="search-btn">搜索</button>
                <button class="reset-btn">重置</button>
                <button onclick="addUser()">添加</button>
            </div>
            <table>
                <thead>
                    <tr>
                        <th><input type="checkbox"></th>
                        <th>序号</th>
                        <th>用户名</th>
                        <th>密码</th>
                        <th>邮箱</th>
                        <th>手机号</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="userTbody"></tbody>
            </table>
        </div>
        <div class="content" id="section-scenic" style="display:none;">
            <div class="table-toolbar">
                <input type="text" placeholder="名字">
                <input type="text" placeholder="位置">
                <input type="text" placeholder="描述">
                <button class="search-btn" onclick="searchScenic()">搜索</button>
                <button class="reset-btn" onclick="resetScenic()">重置</button>
                <button onclick="addScenic()">添加</button>
            </div>
            <table>
                <thead>
                    <tr>
                        <th><input type="checkbox"></th>
                        <th>序号</th>
                        <th>名字</th>
                        <th>位置</th>
                        <th>库存</th>
                        <th>票价</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="scenicTbody"></tbody>
            </table>
        </div>
        <div class="content" id="section-productOrder" style="display:none;">
            <div class="table-toolbar">
                <input type="text" id="searchProductOrderUsername" placeholder="用户名">
                <input type="text" id="searchProductOrderProduct" placeholder="商品名">
                <input type="text" id="searchProductOrderLocation" placeholder="所属地">
                <input type="text" id="searchProductOrderStatus" placeholder="状态">
                <button class="search-btn" onclick="loadProductOrders()">搜索</button>
                <button class="reset-btn" onclick="resetProductOrderSearch()">重置</button>
                <button onclick="window.location.href='order_manage.html'" style="background:#13c2c2;">添加</button>
            </div>
            <table>
                <thead>
                    <tr>
                        <th><input type="checkbox"></th>
                        <th>序号</th>
                        <th>用户名</th>
                        <th>商品名</th>
                        <th>所属地</th>
                        <th>购买数量</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="productOrderTbody"></tbody>
            </table>
            <div id="productOrderModalRoot"></div>
        </div>
        <div class="content" id="section-route" style="display:none;">
            <div class="table-toolbar">
                <input type="text" placeholder="路线名字">
                <input type="text" placeholder="描述">
                <button class="search-btn" onclick="searchRoute()">搜索</button>
                <button class="reset-btn" onclick="resetRoute()">重置</button>
                <button class="add-btn" style="background:#13c2c2;color:#fff;" onclick="window.location.href='route_add.html'">添加</button>
            </div>
            <table>
                <thead>
                    <tr>
                        <th><input type="checkbox"></th>
                        <th>序号</th>
                        <th>旅行社名</th>
                        <th>描述</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="routeTbody"></tbody>
            </table>
        </div>
        <div class="content" id="section-route-spot" style="display:none;">
            <div class="table-toolbar">
                <label>添加景点：</label>
                <select id="scenicSelect"></select>
                <label>选择路线：</label>
                <select id="routeSelect" onchange="loadRouteSpots()"></select>
                <button onclick="addScenicToRoute()">添加到路线</button>
                <button onclick="removeSelectedScenicFromRoute()">批量移除</button>
            </div>
            <table>
                <thead>
                    <tr>
                        <th><input type="checkbox" id="selectAllScenic" onclick="toggleAllScenic()"></th>
                        <th>序号</th>
                        <th>景点名字</th>
                        <th>位置</th>
                        <th>描述</th>
                        <th>票价</th>
                    </tr>
                </thead>
                <tbody id="routeSpotTbody"></tbody>
            </table>
        </div>
        <!-- 路线管理板块（同步example_route） -->
        <div class="content" id="section-scenic-standalone" style="display:none;">
            <div class="table-toolbar">
                <input type="text" placeholder="路线名字" id="searchExampleRouteName">
                <input type="text" placeholder="景点" id="searchExampleRouteScenic">
                <input type="text" placeholder="旅行社" id="searchExampleRouteAgency">
                <input type="text" placeholder="描述" id="searchExampleRouteDesc">
                <button class="search-btn" onclick="searchExampleRoute()">搜索</button>
                <button class="reset-btn" onclick="resetExampleRoute()">重置</button>
                <button class="add-btn" style="background:#13c2c2;color:#fff;" onclick="window.location.href='example_route_add.html'">添加</button>
            </div>
            <table>
                <thead>
                    <tr>
                        <th><input type="checkbox"></th>
                        <th>序号</th>
                        <th>用户名</th>
                        <th>景点</th>
                        <th>旅行社</th>
                        <th>描述</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="exampleRouteTbody"></tbody>
            </table>
        </div>
    </div>
</div>
<script>
// 加载评论数据
function loadComments() {
    fetch('/api/commentNew', { method: 'GET' })
        .then(response => response.json())
        .then(data => {
            var tbody = document.getElementById('commentTbody');
            tbody.innerHTML = '';
            if (Array.isArray(data) && data.length > 0) {
                data.forEach(function(item, idx) {
                    var tr = document.createElement('tr');
                    tr.innerHTML =
                        '<td><input type="checkbox"></td>' +
                        '<td>' + (idx + 1) + '</td>' +
                        '<td class="editable" data-field="userId" data-id="' + item.id + '">' + item.userId + '</td>' +
                        '<td class="editable" data-field="scenicSpot" data-id="' + item.id + '">' + item.scenicSpot + '</td>' +
                        '<td class="editable" data-field="content" data-id="' + item.id + '">' + (item.content || '') + '</td>' +
                        '<td class="editable" data-field="createTime" data-id="' + item.id + '">' + (item.createTime || '') + '</td>' +
                        '<td>' +
                        '<button class="action-btn delete" onclick="deleteRow(' + item.id + ')">删除</button>' +
                        '</td>';
                    tbody.appendChild(tr);
                });
                bindCommentEditEvent();
            } else {
                var tr = document.createElement('tr');
                tr.innerHTML = '<td colspan="7">暂无数据</td>';
                tbody.appendChild(tr);
            }
        });
}
// 编辑功能
function editRow(id) {
    // 获取当前行内容
    var tr = Array.from(document.querySelectorAll('#commentTbody tr')).find(tr => tr.children[1].innerText == id);
    var content = tr.children[4].innerText;
    var newContent = prompt('修改评论内容：', content);
    if (newContent !== null) {
        var comment = {
            id: id,
            userId: tr.children[2].innerText,
            scenicSpotId: tr.children[3].innerText,
            content: newContent,
            createTime: tr.children[5].innerText
        };
        fetch('/api/comment', {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(comment)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('修改成功');
                loadComments();
            } else {
                alert('修改失败');
            }
        });
    }
}
// 删除功能
function deleteRow(id) {
    if (confirm('确定要删除这条评论吗？')) {
        fetch('/api/commentNew/' + id, { method: 'DELETE' })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('删除成功');
                    loadComments();
                } else {
                    alert('删除失败');
                }
            });
    }
}
// 新增：通过用户名查找用户ID
function getUserIdByUsername(username) {
    return fetch('/api/user/byName?username=' + encodeURIComponent(username))
        .then(res => res.json())
        .then(data => data && data.id ? data.id : null);
}
// 新增：通过景点名查找景点ID
function getScenicSpotIdByName(name) {
    return fetch('/api/scenic/byName?name=' + encodeURIComponent(name))
        .then(res => res.json())
        .then(data => data && data.id ? data.id : null);
}
// 修改添加评论逻辑
function addComment() {
    window.location.href = 'comment_edit.html';
}
// 表格内评论字段点击跳转编辑
function bindCommentEditEvent() {
    document.querySelectorAll('#commentTbody .editable[data-field="content"]').forEach(function(td) {
        td.style.cursor = 'pointer';
        td.onclick = function() {
            var id = this.getAttribute('data-id');
            window.location.href = 'comment_edit.html?id=' + encodeURIComponent(id);
        };
    });
}
// 绑定添加按钮
window.onload = function() {
    // 同步右上角用户名
    var username = localStorage.getItem('currentUser');
    if (username) {
        var userSpan = document.querySelector('.header .username');
        if (userSpan) userSpan.textContent = username;
    }
    loadComments();
    document.querySelector('#section-comment .search-btn').onclick = searchComment;
    document.querySelector('#section-comment .reset-btn').onclick = resetComment;
    document.querySelector('.table-toolbar button:last-child').onclick = addComment;
};
function showSection(section) {
    document.getElementById('section-comment').style.display = section === 'comment' ? 'block' : 'none';
    document.getElementById('section-user').style.display = section === 'user' ? 'block' : 'none';
    document.getElementById('section-scenic').style.display = section === 'scenic' ? 'block' : 'none';
    document.getElementById('section-productOrder').style.display = section === 'productOrder' ? 'block' : 'none';
    document.getElementById('section-route').style.display = section === 'route' ? 'block' : 'none';
    document.getElementById('section-route-spot').style.display = section === 'routeSpot' ? 'block' : 'none';
    document.getElementById('section-scenic-standalone').style.display = section === 'scenicStandalone' ? 'block' : 'none';
    document.getElementById('menu-comment').classList.toggle('active', section === 'comment');
    document.getElementById('menu-user').classList.toggle('active', section === 'user');
    document.getElementById('menu-scenic').classList.toggle('active', section === 'scenic');
    document.getElementById('menu-productOrder').classList.toggle('active', section === 'productOrder');
    document.getElementById('menu-route').classList.toggle('active', section === 'route');
    document.getElementById('menu-route-spot').classList.toggle('active', section === 'routeSpot');
    if(section === 'user') loadUsers();
    if(section === 'scenic') loadScenics();
    if(section === 'comment') loadComments();
    if(section === 'route') loadRoutes();
    if(section === 'routeSpot') loadRouteSpotPage();
    if(section === 'productOrder') loadProductOrders();
    if(section === 'scenicStandalone') loadExampleRoutes();
}
// 景点管理相关JS
function loadScenics() {
    fetch('/api/scenic', { method: 'GET' })
        .then(response => response.json())
        .then(data => {
            var tbody = document.getElementById('scenicTbody');
            tbody.innerHTML = '';
            if (Array.isArray(data) && data.length > 0) {
                data.forEach(function(item, idx) {
                    var tr = document.createElement('tr');
                    tr.innerHTML =
                        '<td><input type="checkbox"></td>' +
                        '<td>' + (idx + 1) + '</td>' +
                        '<td class="editable" data-field="name" data-id="' + item.id + '">' + (item.name || '') + '</td>' +
                        '<td class="editable" data-field="location" data-id="' + item.id + '">' + (item.location || '') + '</td>' +
                        '<td class="editable" data-field="stock" data-id="' + item.id + '">' + (item.stock || '') + '</td>' +
                        '<td class="editable" data-field="ticketPrice" data-id="' + item.id + '">' + (item.ticketPrice || '') + '</td>' +
                        '<td><button class="action-btn delete" onclick="deleteScenic(' + item.id + ')">删除</button></td>';
                    tbody.appendChild(tr);
                });
                bindScenicEditEvent();
            } else {
                var tr = document.createElement('tr');
                tr.innerHTML = '<td colspan="7">暂无数据</td>';
                tbody.appendChild(tr);
            }
        });
}
function addScenic() {
    window.location.href = 'scenic_manage.html';
}
function deleteScenic(id) {
    if (confirm('确定要删除该景点吗？')) {
        fetch('/api/scenic/' + id, { method: 'DELETE' })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('删除成功');
                    loadScenics();
                } else {
                    alert(data.message || '删除失败');
                }
            });
    }
}
function searchScenic() {
    var name = document.querySelector('#section-scenic input[placeholder="名字"]').value;
    var location = document.querySelector('#section-scenic input[placeholder="位置"]').value;
    var stock = document.querySelector('#section-scenic input[placeholder="描述"]').value;
    fetch('/api/scenic?name=' + encodeURIComponent(name), { method: 'GET' })
        .then(response => response.json())
        .then(data => {
            var tbody = document.getElementById('scenicTbody');
            tbody.innerHTML = '';
            if (Array.isArray(data) && data.length > 0) {
                data = data.filter(function(item) {
                    return (!location || item.location.indexOf(location) !== -1) && (!stock || item.stock.indexOf(stock) !== -1);
                });
                data.forEach(function(item, idx) {
                    var tr = document.createElement('tr');
                    tr.innerHTML =
                        '<td><input type="checkbox"></td>' +
                        '<td>' + (idx + 1) + '</td>' +
                        '<td class="editable" data-field="name" data-id="' + item.id + '">' + (item.name || '') + '</td>' +
                        '<td class="editable" data-field="location" data-id="' + item.id + '">' + (item.location || '') + '</td>' +
                        '<td class="editable" data-field="stock" data-id="' + item.id + '">' + (item.stock || '') + '</td>' +
                        '<td class="editable" data-field="ticketPrice" data-id="' + item.id + '">' + (item.ticketPrice || '') + '</td>' +
                        '<td><button class="action-btn delete" onclick="deleteScenic(' + item.id + ')">删除</button></td>';
                    tbody.appendChild(tr);
                });
            } else {
                var tr = document.createElement('tr');
                tr.innerHTML = '<td colspan="7">暂无数据</td>';
                tbody.appendChild(tr);
            }
        });
}
function resetScenic() {
    document.querySelector('#section-scenic input[placeholder="名字"]').value = '';
    document.querySelector('#section-scenic input[placeholder="位置"]').value = '';
    document.querySelector('#section-scenic input[placeholder="描述"]').value = '';
    loadScenics();
}
// 用户管理相关JS
function loadUsers() {
    fetch('/api/user', { method: 'GET' })
        .then(response => response.json())
        .then(data => {
            var tbody = document.getElementById('userTbody');
            tbody.innerHTML = '';
            if (Array.isArray(data) && data.length > 0) {
                data.forEach(function(item, idx) {
                    var tr = document.createElement('tr');
                    tr.innerHTML =
                        '<td><input type="checkbox"></td>' +
                        '<td>' + (idx + 1) + '</td>' +
                        '<td class="editable" data-field="username" data-id="' + item.id + '">' + (item.username || '') + '</td>' +
                        '<td class="editable" data-field="password" data-id="' + item.id + '">' + (item.password || '') + '</td>' +
                        '<td class="editable" data-field="email" data-id="' + item.id + '">' + (item.email || '') + '</td>' +
                        '<td class="editable" data-field="phone" data-id="' + item.id + '">' + (item.phone || '') + '</td>' +
                        '<td><button class="action-btn delete" onclick="deleteUser(' + item.id + ')">删除</button></td>';
                    tbody.appendChild(tr);
                });
                document.querySelectorAll('#userTbody .editable').forEach(function(td) {
                    td.onclick = function() {
                        var oldValue = this.innerText;
                        var field = this.getAttribute('data-field');
                        var id = this.getAttribute('data-id');
                        var newValue = prompt('请输入新的内容：', oldValue);
                        if (newValue !== null && newValue !== oldValue) {
                            var tr = this.parentNode;
                            var tds = tr.getElementsByTagName('td');
                            var user = {
                                id: id,
                                username: tds[2].innerText,
                                password: tds[3].innerText,
                                email: tds[4].innerText,
                                phone: tds[5].innerText
                            };
                            user[field] = newValue;
                            fetch('/api/user', {
                                method: 'PUT',
                                headers: { 'Content-Type': 'application/json' },
                                body: JSON.stringify(user)
                            })
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    alert('修改成功');
                                    loadUsers();
                                } else {
                                    alert('修改失败');
                                }
                            });
                        }
                    };
                });
            } else {
                var tr = document.createElement('tr');
                tr.innerHTML = '<td colspan="7">暂无数据</td>';
                tbody.appendChild(tr);
            }
        });
}
function addUser() {
    var username = prompt('请输入用户名：');
    if (!username) { alert('用户名不能为空！'); return; }
    var password = prompt('请输入密码：');
    if (!password) { alert('密码不能为空！'); return; }
    var email = prompt('请输入邮箱：');
    var phone = prompt('请输入手机号：');
    var user = { username: username, password: password, email: email, phone: phone };
    fetch('/api/user', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(user)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('添加成功');
            loadUsers();
        } else {
            alert(data.message || '添加失败');
        }
    });
}
function deleteUser(id) {
    if (confirm('确定要删除该用户吗？')) {
        fetch('/api/user/' + id)
            .then(response => response.json())
            .then(user => {
                fetch('/api/user/' + id, { method: 'DELETE' })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            alert('删除成功');
                            var currentUser = localStorage.getItem('currentUser');
                            if (user && user.username === currentUser) {
                                localStorage.removeItem('currentUser');
                                window.location.href = 'login.html';
                            } else {
                                loadUsers();
                            }
                        } else {
                            alert(data.message || '删除失败');
                        }
                    });
            });
    }
}
// 旅行社管理相关JS
function loadRoutes() {
    fetch('/api/route', { method: 'GET' })
        .then(response => response.json())
        .then(data => {
            var tbody = document.getElementById('routeTbody');
            tbody.innerHTML = '';
            if (Array.isArray(data) && data.length > 0) {
                data.forEach(function(item, idx) {
                    var tr = document.createElement('tr');
                    tr.innerHTML =
                        '<td><input type="checkbox"></td>' +
                        '<td>' + (idx + 1) + '</td>' +
                        '<td class="editable" data-field="name" data-id="' + item.id + '">' + (item.name || '') + '</td>' +
                        '<td class="editable" data-field="description" data-id="' + item.id + '">' + (item.description || '') + '</td>' +
                        '<td><button class="action-btn delete" onclick="deleteRoute(' + item.id + ')">删除</button></td>';
                    tbody.appendChild(tr);
                });
            } else {
                var tr = document.createElement('tr');
                tr.innerHTML = '<td colspan="5">暂无数据</td>';
                tbody.appendChild(tr);
            }
        });
}
function addRoute() {
    var name = prompt('请输入旅行社名称：');
    if (!name) { alert('名称不能为空！'); return; }
    var description = prompt('请输入旅行社描述：');
    var route = { name: name, description: description };
    fetch('/api/route', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(route)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('添加成功');
            loadRoutes();
        } else {
            alert(data.message || '添加失败');
        }
    });
}
function deleteRoute(id) {
    if (confirm('确定要删除该旅行社吗？')) {
        fetch('/api/route/' + id, { method: 'DELETE' })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('删除成功');
                    loadRoutes();
                } else {
                    alert(data.message || '删除失败');
                }
            });
    }
}
function searchRoute() {
    var name = document.querySelector('#section-route input[placeholder="路线名字"]').value;
    var stock = document.querySelector('#section-route input[placeholder="描述"]').value;
    fetch('/api/route?name=' + encodeURIComponent(name), { method: 'GET' })
        .then(response => response.json())
        .then(data => {
            var tbody = document.getElementById('routeTbody');
            tbody.innerHTML = '';
            if (Array.isArray(data) && data.length > 0) {
                data = data.filter(function(item) {
                    return (!stock || item.stock.indexOf(stock) !== -1);
                });
                data.forEach(function(item, idx) {
                    var tr = document.createElement('tr');
                    tr.innerHTML =
                        '<td><input type="checkbox"></td>' +
                        '<td>' + (idx + 1) + '</td>' +
                        '<td class="editable" data-field="name" data-id="' + item.id + '">' + (item.name || '') + '</td>' +
                        '<td class="editable" data-field="stock" data-id="' + item.id + '">' + (item.stock || '') + '</td>' +
                        '<td><button class="action-btn delete" onclick="deleteRoute(' + item.id + ')">删除</button></td>';
                    tbody.appendChild(tr);
                });
            } else {
                var tr = document.createElement('tr');
                tr.innerHTML = '<td colspan="5">暂无数据</td>';
                tbody.appendChild(tr);
            }
        });
}
function resetRoute() {
    document.querySelector('#section-route input[placeholder="路线名字"]').value = '';
    document.querySelector('#section-route input[placeholder="描述"]').value = '';
    loadRoutes();
}
// 路线-景点管理相关JS
function loadRouteSpotPage() {
    // 加载路线下拉
    fetch('/api/route', { method: 'GET' })
        .then(response => response.json())
        .then(data => {
            var routeSelect = document.getElementById('routeSelect');
            routeSelect.innerHTML = '';
            data.forEach(function(route) {
                var opt = document.createElement('option');
                opt.value = route.id;
                opt.text = route.name;
                opt.setAttribute('data-stock', route.stock || '');
                routeSelect.appendChild(opt);
            });
            loadRouteSpots();
        });
    // 恢复：加载所有景点下拉，显示全部景点
    fetch('/api/scenic', { method: 'GET' })
        .then(response => response.json())
        .then(data => {
            var scenicSelect = document.getElementById('scenicSelect');
            scenicSelect.innerHTML = '';
            data.forEach(function(scenic) {
                var opt = document.createElement('option');
                opt.value = scenic.id;
                opt.text = scenic.name;
                scenicSelect.appendChild(opt);
            });
        });
}
function loadRouteSpots() {
    var routeId = document.getElementById('routeSelect').value;
    // 获取当前路线的描述
    var routeStock = '';
    var routeSelect = document.getElementById('routeSelect');
    for (var i = 0; i < routeSelect.options.length; i++) {
        if (routeSelect.options[i].value == routeId) {
            routeStock = routeSelect.options[i].getAttribute('data-stock') || '';
            break;
        }
    }
    fetch('/api/route-spot/scenic/' + routeId)
        .then(response => response.json())
        .then(data => {
            var tbody = document.getElementById('routeSpotTbody');
            tbody.innerHTML = '';
            if (Array.isArray(data) && data.length > 0) {
                data.forEach(function(item, idx) {
                    var tr = document.createElement('tr');
                    tr.innerHTML =
                        '<td><input type="checkbox" class="scenic-checkbox" value="' + item.id + '"></td>' +
                        '<td>' + (idx + 1) + '</td>' +
                        '<td>' + (item.name || '') + '</td>' +
                        '<td>' + (item.location || '') + '</td>' +
                        '<td>' + routeStock + '</td>' +
                        '<td>' + (item.ticketPrice || '') + '</td>';
                    tbody.appendChild(tr);
                });
            } else {
                var tr = document.createElement('tr');
                tr.innerHTML = '<td colspan="6">暂无数据</td>';
                tbody.appendChild(tr);
            }
        });
}
function addScenicToRoute() {
    var routeId = document.getElementById('routeSelect').value;
    var scenicSpotId = document.getElementById('scenicSelect').value;
    fetch('/api/route-spot/add', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ routeId: Number(routeId), scenicSpotId: Number(scenicSpotId) })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('添加成功');
            loadRouteSpots();
        } else {
            alert(data.message || '添加失败');
        }
    });
}
function removeSelectedScenicFromRoute() {
    var routeId = document.getElementById('routeSelect').value;
    var checked = document.querySelectorAll('.scenic-checkbox:checked');
    if (checked.length === 0) { alert('请先选择要移除的景点'); return; }
    checked.forEach(function(box) {
        fetch('/api/route-spot/remove', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ routeId: Number(routeId), scenicSpotId: Number(box.value) })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                loadRouteSpots();
            }
        });
    });
}
function toggleAllScenic() {
    var checked = document.getElementById('selectAllScenic').checked;
    document.querySelectorAll('.scenic-checkbox').forEach(function(box) {
        box.checked = checked;
    });
}
// 修改景点管理表格内编辑为跳转页面
function bindScenicEditEvent() {
    document.querySelectorAll('#scenicTbody .edit-btn').forEach(function(btn) {
        btn.onclick = function() {
            var id = this.getAttribute('data-id');
            window.location.href = 'scenic_manage.html?id=' + encodeURIComponent(id);
        };
    });
}
function formatProductOrderDate(dateStr) {
    if (!dateStr) return '';
    var d = new Date(dateStr);
    if (isNaN(d.getTime())) return dateStr;
    var y = d.getFullYear();
    var m = (d.getMonth() + 1).toString().padStart(2, '0');
    var day = d.getDate().toString().padStart(2, '0');
    return y + '-' + m + '-' + day;
}
function loadProductOrders() {
    var username = document.getElementById('searchProductOrderUsername').value.trim();
    var product = document.getElementById('searchProductOrderProduct').value.trim();
    var location = document.getElementById('searchProductOrderLocation').value.trim();
    var status = document.getElementById('searchProductOrderStatus').value.trim();
    var url = '/api/order?username=' + encodeURIComponent(username) + '&product=' + encodeURIComponent(product) + '&location=' + encodeURIComponent(location) + '&status=' + encodeURIComponent(status);
    fetch(url, { method: 'GET' })
        .then(response => response.json())
        .then(data => {
            var tbody = document.getElementById('productOrderTbody');
            tbody.innerHTML = '';
            if (Array.isArray(data) && data.length > 0) {
                data.forEach(function(item, idx) {
                    var tr = document.createElement('tr');
                    tr.innerHTML =
                        '<td><input type="checkbox"></td>' +
                        '<td>' + (idx + 1) + '</td>' +
                        '<td>' + (item.username || '') + '</td>' +
                        '<td>' + (item.product || '') + '</td>' +
                        '<td>' + (item.location || '') + '</td>' +
                        '<td>' + (item.quantity || '') + '</td>' +
                        '<td>' +
                        '<button class="action-btn edit" onclick="window.location.href=\'order_manage.html?id=' + encodeURIComponent(item.id) + '\'">编辑</button>' +
                        '<button class="action-btn" onclick="deleteProductOrder(' + encodeURIComponent(item.id) + ')">删除</button>' +
                        '</td>';
                    tbody.appendChild(tr);
                });
            } else {
                var tr = document.createElement('tr');
                tr.innerHTML = '<td colspan="8">暂无数据</td>';
                tbody.appendChild(tr);
            }
        });
}
function resetProductOrderSearch() {
    document.getElementById('searchProductOrderUsername').value = '';
    document.getElementById('searchProductOrderProduct').value = '';
    document.getElementById('searchProductOrderLocation').value = '';
    document.getElementById('searchProductOrderStatus').value = '';
    loadProductOrders();
}
function showProductOrderModal(id) {
    var isEdit = !!id;
    var modal = document.createElement('div');
    modal.className = 'modal-bg';
    modal.innerHTML = `<div class=\"modal-card\">
        <h3>${isEdit ? '编辑订单' : '添加订单'}</h3>
        <form id=\"productOrderForm\">
            <div class=\"form-row\">
                <label>用户名</label>
                <input type=\"text\" id=\"productOrderUsername\" name=\"username\" required placeholder=\"请输入用户名\">
            </div>
            <div class=\"form-row\">
                <label>商品名</label>
                <input type=\"text\" id=\"productOrderProduct\" name=\"product\" required placeholder=\"请输入商品名\">
            </div>
            <div class=\"form-row\">
                <label>所属地</label>
                <input type=\"text\" id=\"productOrderLocation\" name=\"location\" required placeholder=\"请输入所属地\">
            </div>
            <div class=\"form-row\">
                <label>购买日期</label>
                <input type=\"date\" id=\"productOrderDate\" name=\"orderDate\" required>
            </div>
            <div class=\"form-row\">
                <label>状态</label>
                <input type=\"text\" id=\"productOrderStatus\" name=\"status\" required placeholder=\"请输入订单状态\">
            </div>
            <div class=\"form-actions\">
                <button type=\"button\" onclick=\"document.getElementById('productOrderModalRoot').innerHTML=''\">取消</button>
                <button type=\"submit\">保存</button>
            </div>
        </form>
    </div>`;
    document.getElementById('productOrderModalRoot').innerHTML = '';
    document.getElementById('productOrderModalRoot').appendChild(modal);
    if (isEdit) {
        fetch('/api/order/' + id, { method: 'GET' })
            .then(response => response.json())
            .then(item => {
                document.getElementById('productOrderUsername').value = item.username || '';
                document.getElementById('productOrderProduct').value = item.product || '';
                document.getElementById('productOrderLocation').value = item.location || '';
                if (item.orderDate) {
                    var dt = item.orderDate.split('T')[0];
                    document.getElementById('productOrderDate').value = dt;
                }
                document.getElementById('productOrderStatus').value = item.status || '';
            });
    }
    document.getElementById('productOrderForm').onsubmit = function(e) {
        e.preventDefault();
        var order = {
            username: document.getElementById('productOrderUsername').value.trim(),
            product: document.getElementById('productOrderProduct').value.trim(),
            location: document.getElementById('productOrderLocation').value.trim(),
            orderDate: document.getElementById('productOrderDate').value,
            status: document.getElementById('productOrderStatus').value.trim()
        };
        var url = '/api/order' + (isEdit ? ('/' + id) : '');
        var method = isEdit ? 'PUT' : 'POST';
        if (isEdit) order.id = id;
        fetch(url, {
            method: method,
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(order)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('操作成功');
                document.getElementById('productOrderModalRoot').innerHTML = '';
                loadProductOrders();
            } else {
                alert(data.message || '操作失败');
            }
        });
    };
}
function deleteProductOrder(id) {
    if (confirm('确定要删除该订单吗？')) {
        fetch('/api/order/' + id, { method: 'DELETE' })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('删除成功');
                    loadProductOrders();
                } else {
                    alert(data.message || '删除失败');
                }
            });
    }
}
// 评论管理搜索
function searchComment() {
    var content = document.querySelector('#section-comment input[placeholder="评论内容"]').value.trim();
    var userId = document.querySelector('#section-comment input[placeholder="用户ID"]').value.trim();
    var scenicSpot = document.querySelector('#section-comment input[placeholder="景点ID"]').value.trim();
    fetch('/api/commentNew', { method: 'GET' })
        .then(response => response.json())
        .then(data => {
            var tbody = document.getElementById('commentTbody');
            tbody.innerHTML = '';
            if (Array.isArray(data) && data.length > 0) {
                data = data.filter(function(item) {
                    return (!content || (item.content && item.content.indexOf(content) !== -1)) &&
                           (!userId || (item.userId && item.userId.indexOf(userId) !== -1)) &&
                           (!scenicSpot || (item.scenicSpot && item.scenicSpot.indexOf(scenicSpot) !== -1));
                });
                data.forEach(function(item, idx) {
                    var tr = document.createElement('tr');
                    tr.innerHTML =
                        '<td><input type="checkbox"></td>' +
                        '<td>' + (idx + 1) + '</td>' +
                        '<td class="editable" data-field="userId" data-id="' + item.id + '">' + item.userId + '</td>' +
                        '<td class="editable" data-field="scenicSpot" data-id="' + item.id + '">' + item.scenicSpot + '</td>' +
                        '<td class="editable" data-field="content" data-id="' + item.id + '">' + (item.content || '') + '</td>' +
                        '<td class="editable" data-field="createTime" data-id="' + item.id + '">' + (item.createTime || '') + '</td>' +
                        '<td>' +
                        '<button class="action-btn delete" onclick="deleteRow(' + item.id + ')">删除</button>' +
                        '</td>';
                    tbody.appendChild(tr);
                });
            } else {
                var tr = document.createElement('tr');
                tr.innerHTML = '<td colspan="7">暂无数据</td>';
                tbody.appendChild(tr);
            }
        });
}
function resetComment() {
    document.querySelector('#section-comment input[placeholder="评论内容"]').value = '';
    document.querySelector('#section-comment input[placeholder="用户ID"]').value = '';
    document.querySelector('#section-comment input[placeholder="景点ID"]').value = '';
    loadComments();
}
// 用户管理搜索
function searchUser() {
    var username = document.querySelector('#section-user input[placeholder="用户名"]').value.trim();
    var email = document.querySelector('#section-user input[placeholder="邮箱"]').value.trim();
    var phone = document.querySelector('#section-user input[placeholder="手机号"]').value.trim();
    fetch('/api/user', { method: 'GET' })
        .then(response => response.json())
        .then(data => {
            var tbody = document.getElementById('userTbody');
            tbody.innerHTML = '';
            if (Array.isArray(data) && data.length > 0) {
                data = data.filter(function(item) {
                    return (!username || (item.username && item.username.indexOf(username) !== -1)) &&
                           (!email || (item.email && item.email.indexOf(email) !== -1)) &&
                           (!phone || (item.phone && item.phone.indexOf(phone) !== -1));
                });
                data.forEach(function(item, idx) {
                    var tr = document.createElement('tr');
                    tr.innerHTML =
                        '<td><input type="checkbox"></td>' +
                        '<td>' + (idx + 1) + '</td>' +
                        '<td class="editable" data-field="username" data-id="' + item.id + '">' + (item.username || '') + '</td>' +
                        '<td class="editable" data-field="password" data-id="' + item.id + '">' + (item.password || '') + '</td>' +
                        '<td class="editable" data-field="email" data-id="' + item.id + '">' + (item.email || '') + '</td>' +
                        '<td class="editable" data-field="phone" data-id="' + item.id + '">' + (item.phone || '') + '</td>' +
                        '<td><button class="action-btn delete" onclick="deleteUser(' + item.id + ')">删除</button></td>';
                    tbody.appendChild(tr);
                });
            } else {
                var tr = document.createElement('tr');
                tr.innerHTML = '<td colspan="7">暂无数据</td>';
                tbody.appendChild(tr);
            }
        });
}
function resetUser() {
    document.querySelector('#section-user input[placeholder="用户名"]').value = '';
    document.querySelector('#section-user input[placeholder="邮箱"]').value = '';
    document.querySelector('#section-user input[placeholder="手机号"]').value = '';
    loadUsers();
}
function loadExampleRoutes() {
    fetch('/api/exampleRoute', { method: 'GET' })
        .then(response => response.json())
        .then(data => {
            var tbody = document.getElementById('exampleRouteTbody');
            tbody.innerHTML = '';
            if (Array.isArray(data) && data.length > 0) {
                data.forEach(function(item, idx) {
                    var tr = document.createElement('tr');
                    tr.innerHTML =
                        '<td><input type="checkbox"></td>' +
                        '<td>' + (idx + 1) + '</td>' +
                        '<td>' + (item.name || '') + '</td>' +
                        '<td>' + (item.scenic || '') + '</td>' +
                        '<td>' + (item.agency || '') + '</td>' +
                        '<td>' + (item.description || '') + '</td>' +
                        '<td><button class="action-btn delete" onclick="deleteExampleRoute(' + item.id + ')">删除</button></td>';
                    tbody.appendChild(tr);
                });
            } else {
                var tr = document.createElement('tr');
                tr.innerHTML = '<td colspan="7">暂无数据</td>';
                tbody.appendChild(tr);
            }
        });
}
function searchExampleRoute() {
    var name = document.getElementById('searchExampleRouteName').value.trim();
    var scenic = document.getElementById('searchExampleRouteScenic').value.trim();
    var agency = document.getElementById('searchExampleRouteAgency').value.trim();
    var desc = document.getElementById('searchExampleRouteDesc').value.trim();
    fetch('/api/exampleRoute', { method: 'GET' })
        .then(response => response.json())
        .then(data => {
            var tbody = document.getElementById('exampleRouteTbody');
            tbody.innerHTML = '';
            if (Array.isArray(data) && data.length > 0) {
                data = data.filter(function(item) {
                    return (!name || (item.name && item.name.indexOf(name) !== -1)) &&
                           (!scenic || (item.scenic && item.scenic.indexOf(scenic) !== -1)) &&
                           (!agency || (item.agency && item.agency.indexOf(agency) !== -1)) &&
                           (!desc || (item.description && item.description.indexOf(desc) !== -1));
                });
                data.forEach(function(item, idx) {
                    var tr = document.createElement('tr');
                    tr.innerHTML =
                        '<td><input type="checkbox"></td>' +
                        '<td>' + (idx + 1) + '</td>' +
                        '<td>' + (item.name || '') + '</td>' +
                        '<td>' + (item.scenic || '') + '</td>' +
                        '<td>' + (item.agency || '') + '</td>' +
                        '<td>' + (item.description || '') + '</td>' +
                        '<td><button class="action-btn delete" onclick="deleteExampleRoute(' + item.id + ')">删除</button></td>';
                    tbody.appendChild(tr);
                });
            } else {
                var tr = document.createElement('tr');
                tr.innerHTML = '<td colspan="7">暂无数据</td>';
                tbody.appendChild(tr);
            }
        });
}
function resetExampleRoute() {
    document.getElementById('searchExampleRouteName').value = '';
    document.getElementById('searchExampleRouteScenic').value = '';
    document.getElementById('searchExampleRouteAgency').value = '';
    document.getElementById('searchExampleRouteDesc').value = '';
    loadExampleRoutes();
}
function deleteExampleRoute(id) {
    if (confirm('确定要删除该路线吗？')) {
        fetch('/api/exampleRoute/' + id, { method: 'DELETE' })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('删除成功');
                    loadExampleRoutes();
                } else {
                    alert(data.message || '删除失败');
                }
            });
    }
}
</script>
</body>
</html> 